<?php

// +----------------------------------------------------------------------
// | SinianAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2019 祀念网络科技有限公司 [ http://www.sinianwork.cc ]
// +----------------------------------------------------------------------
// | 官方网站: http://demo.sinianwork.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：
// | github 代码仓库：
// +----------------------------------------------------------------------

namespace app\api\controller;
use app\data\model\ControlPlanModel;
use app\data\model\ControlPlanListModel;
use app\data\model\ControlPlanItemModel;
use app\data\model\ControlAccessoryModel;
use app\data\model\ControlMaterialModel;
use app\data\model\EnterStorehouseItemModel;
use app\data\model\EnterStorehouseModel;
use app\data\model\StorehouseModel;
use think\facade\Db;
use think\facade\Request;
use think\admin\extend\CodeExtend;
use think\admin\Controller;

/**
 * 计划审核接口
 * Class index
 * @package app\index\controller
 */
class User extends Controller
{
    /**
     * 用户登陆
     */
    public function login()
    {
        $data = $this->_vali([
            'username.require' => '登录账号不能为空!',
            'username.min:4'   => '登录账号不能少于4位字符!',
            'password.require' => '登录密码不能为空!',
            'password.min:4'   => '登录密码不能少于4位字符!',
        ]);
        // 用户信息验证
        $map = ['is_deleted' => '0', 'username' => $data['username']];
        $user = Db::name('SystemUser')->where($map)->order('id desc')->find();
        if (empty($user)) $this->error('登录账号或密码错误，请重新输入!');
        // dump(md5(md5($user['password'] ).null));die;
        if ($user['password'] !== md5($data['password'])) {
            $this->error('登录账号或密码错误，请重新输入!');
        }
        if (empty($user['status'])) $this->error('账号已经被禁用，请联系管理员!');
        if(!$user['qr_code']){
            $url = strval($user['id']);
            $errorCorrectionLevel = "L"; // 纠错级别：L、M、Q、H
            $matrixPointSize = "4"; // 点的大小：1到10
            header("Content-type:image/png");
            require "../vendor/phpqrcode/phpqrcode.php";
            $qrCode = new \QRcode();
            $path = "./upload/qrcode/";//生成的二维码所在目录
            $time = $user['id'].'.png';//生成的二维码文件名
            $fileName = $path.$time;//1.拼装生成的二维码文件路径
            $qrImg = $qrCode->png($url, $fileName, $errorCorrectionLevel, $matrixPointSize,true);
            $res = Db::name('SystemUser')->where($map)->update(['qr_code'=>'/upload/qrcode/'.$user['id'].'.png']);
            if($res === false){
                $this->error('服务器错误，请重试');
            }
            $user['qr_code'] = '/upload/qrcode/'.$user['id'].'.png';
        }
        Db::name('SystemUser')->where(['id' => $user['id']])->update([
            'login_at' => Db::raw('now()'), 'login_ip' => Request::ip(), 'login_num' => Db::raw('login_num+1'),
        ]);
        $json = array(
            'id'=>$user['id'],
            'username'=>$user['username'],
            'nickname'=>$user['nickname'],
            'phone'=>$user['contact_phone'],
            'parent_id'=>$user['parent_id'],
            'authorize'=>$user['authorize'],
            'qr_code'=>$user['qr_code'],
        );
        $this->success('ok',$json,1);
    }
    /**
     * 获取计划列表
     */
    public function getPlanApply(){
        $data = input('post.');
        if(!isset($data['admin_id']) || !$data['admin_id']) {
            $this->error('请先登陆');
        }
        if($data['admin_id'] == 10000 || $data['authorize'] == 7){
            $where = array();
        }else{
            $where[] = ['admin_id','=',$data['admin_id']];
        }
        //搜索
        if(isset($data['plan_title']) and !empty($data['plan_title'])){
            $str = substr( $data['plan_title'], 0, 1 );
            if($str == 'J'){
                $where[] = array('id','like',$data['plan_title'].'%');
            }else{
                $where[] = array('plan_title','like',$data['plan_title'].'%');
            }
        }
        $where[] = array('deleted','=',0);
        $planList = ControlPlanModel::where($where)->order('id desc')->limit(($data['page']-1)*$data['size'], $data['size'])->field('id,plan_title,deleted,status,cate_id,plan_type,admin_name,admin_id')->select();
        foreach ($planList as $k=>$v){
            $planList[$k]['merge_time'] = Db::name('sn_control_plan_merge')->where('id',$v['merge_id'])->value('merge_time');
            $planList[$k]['keshi_name'] = Db::name('system_user')->where('id',$v['keshi_id'])->value('username');
        }
        $this->success('ok',$planList,1);

    }

    /**
     * 获取计划详情
     */
    public function getPlanInfo(){
        $data = input('post.');
        if(!$data['plan_id']) {$this->error('无此计划');}
        $where = array(
            'id'=>$data['plan_id']
        );
        $planList = ControlPlanModel::where($where)->find();
        $planList['plan_list'] = ControlPlanListModel::where('plan_id',$data['plan_id'])->select()->toArray();
        $this->success('ok',$planList,1);

    }
    /**
     * 获取物资列表
     */
    public function getCateList(){
        $data = input('post.');
        if(!isset($data['admin_id']) || !$data['admin_id']) {$this->error('请先登陆');}
        if(!isset($data['cate_id']) || !$data['cate_id']){$this->error('该分类不存在');}
        //搜索
        if(isset($data['material_model'])){
            $where[]=['material_model','like','%'.$data['material_model'].'%'];
        }
        if(isset($data['material_code'])){
            if(is_numeric($data['material_code'])){
                $where[]=['material_code','like',$data['material_code'].'%'];
            }else{
                $where[]=['material_name','like','%'.$data['material_code'].'%'];
            }
        }else{
            $where = [];
        }
        //状态
        if(isset($data['status'])){
            $where[]=['deleted','=',1];
        }
        if($data['cate_id'] == 1){
            $cateList = ControlMaterialModel::where($where)->whereRaw('char_length(material_code) = 13')->limit(($data['page']-1)*$data['size'], $data['size'])->select();
        }elseif ($data['cate_id'] == 2) {
            $cateList = ControlAccessoryModel::where($where)->whereRaw('char_length(material_code) = 13')->limit(($data['page']-1)*$data['size'], $data['size'])->select();
        }else{
            $cateList = [];
        }
        $this->success('ok',$cateList,1);
    }

    /**
     * 获取添加计划页面
     */
    public function getAddPlanList(){
        $data = input('post.');
        if(!$data['admin_id']){return $this->error('请先登陆');}
        $where['is_deleted'] = 0;
        if(isset($data['authorize']) and $data['authorize'] == 10000){
            $list['keshi_list'] = [];
        }else{
            $list['keshi_list'] = Db::name('system_user')->where('authorize',$data['authorize']+1)->where($where)->field('id,nickname,username')->select()->toArray();
        }
        return $this->success('ok',$list,1);

    }
    /**
     * 获取上级信息
     */
    public function getParentInfo()
    {
        $id = input('id');
        $info = Db::name('system_user')->where(['id' => $id, 'is_deleted' => '0'])->value('parent_id');
        if($info == 0){$this->success('ok',[],1);}
        $list = Db::name('system_user')->where(['id' => $info, 'is_deleted' => '0'])->field('id,parent_id,username')->select();
        $this->error('ok',$list,1);

    }

    /**
     * 添加计划
     */
    public function addPlanApply(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!isset($data['plan_list']) || empty($data['plan_list'])){$this->error('材料列表不可为空');}
        if(!isset($data['plan_type'])){$this->error('计划类型不可为空');}
        $plan_list = json_decode($data['plan_list'],true);
        foreach ($plan_list as $ks => $vs){
            if(!$vs['material_code'] || empty($vs['material_code'])){$this->error($vs['material_name'].'编号不可为空');}
            if(!$vs['material_num'] || empty($vs['material_num'])){$this->error($vs['material_name'].'('.$vs['material_code'].')'.'数量不可为0');}
        }
        $userInfo = Db::name('system_user')->where('id',$data['admin_id'])->where('is_deleted',0)->field('id,nickname,username,authorize')->find();
        if(!isset($data['id'])){
            //添加
            //获取标题
            if($data['plan_type']){
                //获取计划时间
                $yuefen = date('m',time())+1;
                if($yuefen>12){
                    $nian = date('Y',time())+1;
                    $yuefen = 1;
                }else{
                    $nian = date('Y',time());
                }
                $title = $nian.'年'.$yuefen.'月（月度计划）';
                $data['plan_data_status'] = date('Ym',time())+1;
                //判断当月计划是否有提交过
                $wheres = array(
                    'plan_data_status'=>$nian.$yuefen,
                    'admin_id'=>$userInfo['id'],
                    'plan_type'=>1,
                );
                $isSubmit = ControlPlanModel::where($wheres )->value('status');
                if($isSubmit && $isSubmit['status'] != '-1'){
                    $this->error($nian.'年'.$yuefen .'月计划已提交，不可重复提交');
                }
            }else{
                //获取计划时间
                $yuefen = date('m',time());
                if($yuefen>12){
                    $nian = date('Y',time())+1;
                    $yuefen = 1;
                }else{
                    $nian = date('Y',time());
                }
                $title = $nian.'年'.$yuefen.'月（临时计划）';
                $data['plan_data_status'] = date('Ym',time());
                //判断当月临时计划是否已限制提交
                $wheres = array(
                    'plan_data_status'=>$nian.$yuefen,
                    'admin_id'=>$userInfo['id'],
                    'plan_type'=>0,
                );
                // $isSubmitCount = PlanApplyModel::where($wheres)->count();
                // if($isSubmitCount > 2){
                //     $this->error($nian.'年'.$yuefen .'当月临时计划提交次数已上限');
                // }
            }
            $data['plan_title'] = $title;
            $data['admin_id'] = $userInfo['id'];
            $data['admin_name'] = $userInfo['username'];
        }
        //获取提交时间
        $data['plan_time'] = time();
        $data['status'] = 0;
        //开启事务
        Db::startTrans();
        try{
            // 判断是来自ADD还是EDIT
            if(!isset($data['id'])){
                $is_set = false;
                // 生成计划ID
                $data['id'] = CodeExtend::uniqidNumber(10,'J');
            }else{
                $is_set = true;
                //删除计划流程数据
                $time_del = Db::name('sn_control_plan_time')->where('collect_id',$data['id'])->delete();
                if (!$time_del) {throw new \Exception("流程更新错误");}
                //删除计划子表数据
                $listDel = Db::name('sn_control_plan_list')->where('plan_id',$data['id'])->delete();
                if (!$listDel) {throw new \Exception("物资更新错误");}
            }
            //如果发起人为业务科室
            if($userInfo['authorize'] >1){
                //添加一条合并数据
                $iet_arr = array(
                    'title' => date('Y年m月d日',time()).'业务科室计划',
                    'plan_ids'=>$data['id'],
                    'admin_id'=>$userInfo['id'],
                    'admin_name'=>$userInfo['username'],
                    'merge_time'=>date('Y-m-d H:i:s',time()),
                    'admin_nickname'=>$userInfo['nickname'],
                    'plan_status'=>3,
                    'below_admin_id'=>$data['keshi_id']
                );
                $data['merge_id'] = Db::name('sn_control_plan_merge')->insertGetId($iet_arr);
            }
            $PlanApplyModel = new ControlPlanModel();
            if($is_set){
                $applyAll = $PlanApplyModel->where('id',$data['id'])->update($data);
            }else{
                $applyAll = $PlanApplyModel->insert($data);
            }
            //计划流程数据
            if (!$applyAll) {throw new \Exception("服务器错误");} 
            // 子表数据添加
            $cate_list = array();
            //组合数组
            foreach ($plan_list as $k=>$v){
                $cate_list[$k]['material_code'] = $v['material_code'];
                $cate_list[$k]['material_name'] = $v['material_name'];
                $cate_list[$k]['material_model'] = $v['material_model'];
                $cate_list[$k]['material_unit'] = $v['material_unit'];
                $cate_list[$k]['material_price'] = $v['material_price'];
                $cate_list[$k]['material_num'] = $v['material_num'];
                $cate_list[$k]['material_xjprice'] = sprintf("%01.2f", $v['material_price'] * $v['material_num']);
                $cate_list[$k]['admin_id'] = $data['admin_id'];
                $cate_list[$k]['admin_name'] = $data['admin_name'];
                $cate_list[$k]['plan_id'] = $data['id'];
                $cate_list[$k]['plan_time'] = date('Y-m-d H:i:s',time());
                $cate_list[$k]['cate_id'] = $data['cate_id'];
            }
            //计划子表数据
            $applyAll = Db::name('sn_control_plan_list')->insertAll($cate_list);
            if (!$applyAll) {throw new \Exception("服务器错误");}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());die;
        }
        $this->success('ok','',1);
    }

    /**
     * 获取计划流程
     */
    public function getPlanApplyProcedure(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!isset($data['plan_id']) || !$data['plan_id']){$this->error('该计划不存在');}
        $where = array(
            'collect_id'=>$data['plan_id']
        );
        $plan_list = Db::name('sn_control_plan_time')->where($where)->order('admin_authorize asc')->select();
        $this->success('ok',$plan_list,1);
    }


    /**
     * 删除计划
     */
    public function deletePlanApply(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!isset($data['plan_id']) || !$data['plan_id']){$this->error('该计划不存在');}
        $where = array('collect_id'=>$data['plan_id']);
        //开启事务
        Db::startTrans();
        try{
            // 删除计划流程数据
            $plan = ControlPlanModel::where('id',$data['plan_id'])->delete();
            if (!$plan) {throw new \Exception("服务器错误");}
            // 流程表数据
            $plan_list = Db::name('sn_control_plan_time')->where('collect_id',$data['plan_id'])->delete();
            if (!$plan_list) {throw new \Exception("服务器错误");}
            // 删除计划子表数据
            $listDel = Db::name('sn_control_plan_list')->where('plan_id',$data['plan_id'])->delete();
            if ($listDel === false) {throw new \Exception("服务器错误");}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());die;
        }
        $this->success('ok',[],1);

    }

    /**
     * 获取计划详情
     */
    public function getPlanApplyDetail(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!isset($data['plan_id']) || !$data['plan_id']){$this->error('该计划不存在');}
        $where = array(
            'deleted'=>0,
            'id'=>$data['plan_id']
        );
        $info = ControlPlanModel::where($where)->order('id desc')->find();
        $info['plan_list'] = Db::name('sn_control_plan_list')->where('plan_id',$data['plan_id'])->select();
        $info['total'] = 0;
        if($info['plan_list']){
            foreach ($info['plan_list'] as $v){
                $info['total'] += $v['material_xjprice'];
            }
        }else{
            $info['plan_list'] = [];
        }
        $this->success('ok',$info,1);

    }

    /**
     * 获取计划审核列表
     */
    public function getToExamineList(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!isset($data['authorize'])){$this->error('权限不存在');}
        //搜索
        if(isset($data['material_model'])){
            $where[]=['material_model','like','%'.$data['material_model'].'%'];
        }
        if(isset($data['material_code']) && $data['material_code']){
            $str = substr( $data['material_code'], 0, 1 );
            if($str == 'J'){
                $where[]=['id','like',$data['material_code'].'%'];
            }else{
                $where[]=['plan_title','like','%'.$data['material_code'].'%'];
            }
        }else{
            $where = [];
        }
        //权限重构
        $where[] = array( 'deleted','=', 0);
        //状态
        if(isset($data['status']) && $data['status']){
            $where[]=['status','=',$data['status']];
        }else{
            $where[] = array( 'status','<>', -1);
        }
        if($data['authorize'] == 2){
            //队干
            $where[] = array('keshi_id','=',$data['admin_id']);
            $list = ControlPlanModel::where($where)->order('id desc')->limit(($data['page']-1)*$data['size'], $data['size'])->select()->toArray();
            foreach ($list as $k=>$v){
                $list[$k]['merge_time'] = Db::name('sn_control_plan_merge')->where('id',$v['merge_id'])->value('merge_time');
                $list[$k]['keshi_name'] = Db::name('system_user')->where('id',$v['keshi_id'])->value('username');
            }
        }else{
            $list = [];
        }
        
        $this->success('ok',$list,1);

    }


    /**
     * 审核通过
     */
    public function toResume()
    {
        $authorize = input('authorize');
        if(!input('admin_id')){$this->error('请先登陆');}
        $plan_id = input('plan_id');
        $planData = ControlPlanModel::where('id',$plan_id)->find();
        //获取计划类型
        if($authorize >=7 and $planData['plan_data_status'] != date('Ym',time())){
            if($planData['plan_type']){
                $this->error('月度计划请在次月审核');
            }else{
                $this->error('该临时计划已作废');
            }
        }
        //开启事务
        Db::startTrans();
        try{
            //主表数据修改
            $controlPlanItem = Db::name('sn_control_plan_time')->where('collect_id',$plan_id)->where('status',0)->order('admin_authorize asc')->column('admin_authorize');
            if(isset($controlPlanItem[1]) and $controlPlanItem[1] > 0){
                $planInfo['plan_status'] = $controlPlanItem[1];
            }else{
                $planInfo['plan_status'] = $controlPlanItem[0];
                $planInfo['status'] = 1;
                //获取计划所属人
                $admin_id = $planData['admin_id'];
                //创建库存表
                $sql = created_data('sn_enter_storehouse_'.$admin_id);
                Db::execute($sql);
                //获取计划子表数据
                $planList = ControlPlanListModel::where('plan_id',$plan_id)->field('material_code,material_name,material_model,material_unit,material_price,material_num')->column('material_code,material_name,material_model,material_unit,material_price,material_num','material_code');
                //添加个人库存数据
                $adminStorehouse = Db::name('sn_enter_storehouse_'.$admin_id)->whereIn('material_code',array_column($planList,'material_code'))->column('*','material_code');
                if(count($planList) == count($adminStorehouse)){
                    foreach ($planList as $k=>$v){
                        $planList[$k]['material_num'] = $v['material_num'] + $adminStorehouse[$k]['material_num'];
                    }
                    //先删除
                    $res = Db::name('sn_enter_storehouse_'.$admin_id)->whereIn('material_code',array_keys($planList))->delete();
                    if (!is_int($res)) {throw new \Exception("服务器错误");}
                    //新增数据
                    $res = Db::name('sn_enter_storehouse_'.$admin_id)->insertAll($planList);
                    if (!is_int($res)) {throw new \Exception("服务器错误");}
                }elseif (count($adminStorehouse) == 0){
                    //新增数据
                    $res = Db::name('sn_enter_storehouse_'.$admin_id)->insertAll($planList);
                    if (!is_int($res)) {throw new \Exception("服务器错误");}
                }else{
                    //比较两个数组的键名，并返回交集
                    $intersect_list = array_intersect_key($planList,$adminStorehouse);
                    foreach ($intersect_list as $k=>$v){
                        $intersect_list[$k]['material_num'] = $v['material_num'] + $adminStorehouse[$k]['material_num'];
                    }
                    //先删除
                    $res = Db::name('sn_enter_storehouse_'.$admin_id)->whereIn('material_code',array_keys($intersect_list))->delete();
                    if (!is_int($res)) {throw new \Exception("服务器错误");}
                    //比较两个数组的键名，并返回差集
                    $diffList = array_diff_key($planList,$adminStorehouse);
                    //合并数据
                    $mergeList = array_merge($intersect_list,$diffList);
                    //新增数据
                    $res = Db::name('sn_enter_storehouse_'.$admin_id)->insertAll($mergeList);
                    if (!is_int($res)) {throw new \Exception("服务器错误");}
                }
            }
            $resut = ControlPlanModel::where('id',$plan_id)->update($planInfo);
            // 判断是否修改成功
            if (!is_int($resut)) {throw new \Exception("服务器错误");}
            // 流程表数据修改
            $planDate = array('status'=>1,'time'=>date('Y-m-d H:i:s',time()));
            if($authorize == 6){
                $whereTime = ['collect_id'=>$plan_id,'admin_authorize'=>6];
            }else{
                $whereTime = ['collect_id'=>$plan_id,'admin_id'=>input('admin_id')];
            }
            $applyTime = Db::name('sn_control_plan_time')->where($whereTime)->update($planDate);
            if (!is_int($applyTime)) {throw new \Exception("服务器错误");}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('ok');
    }


    /**
     * 审核拒绝
     */
    public function toRefusal()
    {
        $username = input('username');
        $admin_id = input('admin_id');
        if(!$admin_id || !$username){$this->error('请先登陆');}
        $plan_id = input('plan_id');
        $refusal_cause = input('refusal_cause');
        $dateTime = date('Y-m-d H:i:s',time());
        $planTime = array('status'=>-1,'time'=>$dateTime,'to_reason'=>$refusal_cause);
        //开启事务
        Db::startTrans();
        try{
            //获取权限id
            $resut = Db::name('sn_control_plan_time')->insertGetId($planTime);
            if (!$resut) {throw new \Exception("服务器错误");}
            $plan_list = ControlPlanModel::where('id',$plan_id)->update(['status' => '-1','plan_status'=>0,'reason_name'=>$username,'reason_id'=>$admin_id,'to_reason'=>$refusal_cause,'reason_time'=>$dateTime]);
            if (!$plan_list) {throw new \Exception("服务器错误");}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());die;
        }
        $this->success('数据更新成功');
    }



    /**
     * 合并计划
     */
    public function mergePlan()
    {
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!$data['authorize'] && $data['authorize'] != 4){$this->error('无权限操作');}
        $idArr = explode(',',$data['plan_ids']);
        if(count($idArr) == 1){$this->error('请选择两个或两个以上合并');}
        $dateTime = date('Y-m-d H:i:s',time());
        $addAr = array(
            'title'=>date('Y年m月d日',time()).'合并计划',
            'plan_ids'=>$data['plan_ids'],
            'admin_id'=>$data['admin_id'],
            'admin_name'=>$data['username'],
            'admin_nickname'=>$data['nickname'],
            'merge_time'=>$dateTime,
            'plan_status'=>$data['authorize'],
            'merge_time'=>$dateTime,
        );
        //开启事务
        Db::startTrans();
        try{
            $plan_apply_merge_id = Db::name('sn_control_plan_merge')->insertGetId($addAr);
            if(!$plan_apply_merge_id){$this->error('服务器错误，请重试~');}
            $planList = ControlPlanModel::whereIn('id',$idArr)->update(['merge_id'=>$plan_apply_merge_id]);
            if(!$planList){$this->error('服务器错误，请重试~');}
            $planList = ControlPlanListModel::whereIn('plan_id',$idArr)->update(['merge_id'=>$plan_apply_merge_id]);
            if(!$planList){$this->error('服务器错误，请重试~');}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('数据合并成功');
    }

    //合并计划列表数据
    public function getPlanMerge(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!$data['authorize']){$this->error('无权限操作');}
        //搜索
        if(isset($data['title'])){
            $where[]=['m.title','like','%'.$data['title'].'%'];
        }else{
            $where = [];
        }
        if($data['authorize'] == 2){
            $where[] = ['m.admin_id','=',$data['admin_id']];
            $plan_merge = Db::name('sn_control_plan_merge')->alias('m')->where($where)->limit(($data['page']-1)*$data['size'], $data['size'])->order('m.id desc')->select()->toArray();
        }elseif($data['authorize'] == 3){
            $where[] = ['m.examine_admin_id','=',$data['admin_id']];
            $plan_merge = Db::name('sn_control_plan_merge')->alias('m')->where($where)->join('system_user u','m.examine_admin_id = u.id')->limit(($data['page']-1)*$data['size'], $data['size'])->order('m.id desc')->field('m.*,u.nickname,u.username,u.authorize')->select()->toArray();
        }else{
            $where[] = ['m.below_admin_id','=',$data['admin_id']];
            $plan_merge = Db::name('sn_control_plan_merge')->alias('m')->where($where)->join('system_user u','m.below_admin_id = u.id')->limit(($data['page']-1)*$data['size'], $data['size'])->order('m.id desc')->field('m.*,u.nickname,u.username,u.authorize')->select()->toArray();
        }
        foreach ($plan_merge as $k=>$v){
            $plan_merge[$k]['below_admin_name'] =Db::name('system_user')->where('id',$v['below_admin_id'])->value('username');
            $plan_merge[$k]['integration_time'] = Db::name('sn_control_plan_integration')->where('id',$v['integration_id'])->value('create_at');
        }
        $this->success('ok',$plan_merge,200);
    }
    
    /**
     * 删除合并计划
     */
    public function getPlanMergeRemove()
    {
        $id = input('post.id');
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        //开启事务
        Db::startTrans();
        try{
            if(ControlPlanModel::where('merge_id',$id)->count()){
                //还原合并数据
                $plan_apply_merge_id = ControlPlanModel::where('merge_id',$id)->update(['merge_id'=>0]);
                if(!$plan_apply_merge_id){$this->error('服务器错误，请重试~');}
                $planList = ControlPlanListModel::where('merge_id',$id)->update(['merge_id'=>0]);
                if(!$planList){$this->error('服务器错误，请重试~');}
            }
            $res = Db::name('sn_control_plan_merge')->where('id',$id)->delete();
            if(!$res){$this->error('服务器错误，请重试~');}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('ok','',200);
    }
    


    //合并计划审批数据
    public function getPlanMergeExamine(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!$data['authorize']){$this->error('请先登陆');}
        if(isset($data['plan_status']) and !$data['plan_status']){$this->error('缺少重要参数');}
        $list['list'] = Db::name('system_user')->where('authorize',$data['plan_status']+1)->where('is_deleted',0)->field('id,nickname,username')->select()->toArray();
        $list['auth_list'] = Db::name('system_auth')->where('status',1)->where('sort','>',$data['authorize'])->select()->toArray();
        $this->success('ok',$list,200);
    }
    
     /**
     * 获取下级审批人信息
     */
    public function getMergeParentInfo()
    {
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        $info = Db::name('system_user')->where(['status' => 1])->where('authorize','=',$data['authorize'])->where('is_deleted',0)->field('id,username,nickname')->select();
        $this->success('ok',$info,200);
    }
    
    // 合并计划审核
    public function MergeToExamine(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!$data['authorize']){$this->error('请先登陆');}
        if(!$data['plan_status']){$this->error('请先选择下级审批权限');}
        if(!$data['id']){$this->error('缺少重要参数');}
        if(!$data['below_admin_id']){$this->error('请先选择下级审批人');}
        if($data['authorize'] == 2){$data['examine_admin_id'] = $data['below_admin_id'];}
        //开启事务
        Db::startTrans();
        try{
            //修改流程表信息
            $plan_ids = ControlPlanListModel::where('merge_id',$data['id'])->group('plan_id')->column('plan_id');
            foreach ($plan_ids as $k=>$v){
                $saveArr[$k]['status'] = 1;
                $saveArr[$k]['time'] = date('Y-m-d H:i:s');
                $saveArr[$k]['to_reason'] = $data['remarks'];
                $saveArr[$k]['collect_id'] = $v;
                $saveArr[$k]['admin_id'] = $data['admin_id'];
                $saveArr[$k]['admin_name'] = $data['username'];
                $saveArr[$k]['admin_authorize'] = $data['authorize'];
                $saveArr[$k]['admin_nickname'] = $data['nickname'];
            }
            $ControlPlanItemModel = new ControlPlanItemModel();
            $plan_item = $ControlPlanItemModel->saveAll($saveArr);
            if(!$plan_item){$this->error('服务器错误');}
            unset($data['authorize']);
            unset($data['username']);
            unset($data['nickname']);
            $mer_id = Db::name('sn_control_plan_merge')->where('id',$data['id'])->update($data);
            if(!$mer_id){$this->error('服务器错误');}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('ok','',200);
    }
    
    
    //合并计划详情
    public function getPlanMergeInfo(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        $where = array( 'id'=>$data['id']);
        $info = Db::name('sn_control_plan_merge')->where($where)->find();
        $userInfo =  Db::name('system_user')->where(['id'=>$info['below_admin_id']])->find();
        if($userInfo){
            $info['below_admin_name'] = $userInfo['username'];
            $info['below_admin_nickname'] = $userInfo['nickname'];
        }else{
            $info['below_admin_name'] = '';
            $info['below_admin_nickname'] = '';
        }
        $plan_list = ControlPlanListModel::whereIn('plan_id',$info['plan_ids'])->group('material_code')->field('*,sum(material_num) as material_num')->order('material_code')->select()->toArray();
        $total = 0;
        foreach ($plan_list as $k=>$v){
            $plan_list[$k]['info'] = ControlPlanListModel::where(['material_code'=>$v['material_code']])->whereIn('plan_id',$info['plan_ids'])->field('merge_id,material_code,admin_name,sum(material_num) as material_num')->order('material_code')->column('admin_name,material_num');
            $plan_list[$k]['material_xjprice'] = sprintf("%01.2f", $v['material_price'] * $v['material_num']);
            $total += sprintf("%01.2f", $v['material_price'] * $v['material_num']);
        }
        $json = ['info'=>$info,'list'=>$plan_list,'total'=>$total];
        $this->success('ok',$json,200);
    }
    
    //合并计划拒绝
    public function mergeRefusal(){
        $data = input('post.');
        $refusal_cause = input('refusal_cause');
        $dateTime = date('Y-m-d H:i:s',time());
        $plan_ids = ControlPlanModel::where('merge_id',$data['merge_id'])->column('id');
        foreach ($plan_ids as $k=>$v){
            $saveArr[$k]['status'] = -1;
            $saveArr[$k]['time'] = $dateTime;
            $saveArr[$k]['to_reason'] = $refusal_cause;
            $saveArr[$k]['collect_id'] = $v;
            $saveArr[$k]['admin_id'] = $data['admin_id'];
            $saveArr[$k]['admin_name'] = $data['username'];
            $saveArr[$k]['admin_authorize'] = $data['authorize'];
            $saveArr[$k]['admin_nickname'] = $data['nickname'];
        }
        //开启事务
        Db::startTrans();
        try{
            $ControlPlanItemModel = new ControlPlanItemModel();
            $plan_item = $ControlPlanItemModel->saveAll($saveArr);
            if (!$plan_item) {$this->error('服务器错误');}
            //批量修改主表计划
            $plan_list = ['status' => '-1','reason_name'=>$data['username'],'reason_id'=>$data['admin_id'],'to_reason'=>$refusal_cause,'reason_time'=>$dateTime,'merge_id'=>0];
            $plan_save = ControlPlanModel::whereIn('id',$plan_ids)->update($plan_list);
            if (!is_int($plan_save)) {$this->error('服务器错误');}
            //批量修改子表计划
            $plan_zi_save = ControlPlanListModel::whereIn('plan_id',$plan_ids)->update(['merge_id'=>0]);
            if (!is_int($plan_zi_save)) {$this->error('服务器错误');}
            $save_data = ['status' => '-1','reason_name'=>$data['username'],'reason_id'=>$data['admin_id'],'to_reason'=>$refusal_cause,'reason_time'=>$dateTime];
            $save_res = Db::name('sn_control_plan_merge')->where('id',$data['merge_id'])->update($save_data);
            if (!is_int($save_res)) {$this->error('服务器错误');}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('ok','',200);
        
    }
    
    
    //计划整合
    public function setIntegration(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        $idArr = explode(',',$data['ids']);
        if(count($idArr) == 1){$this->error('请选择两个或两个以上整合');}
        $dateTime = date('Y-m-d H:i:s',time());
        $addAr = array(
            'title'=>date('Y年m月d日',time()).'计划整合',
            'merge_ids'=>$data['ids'],
            'admin_id'=>$data['admin_id'],
            'admin_name'=>$data['username'],
            'admin_nickname'=>$data['nickname'],

        );
        //开启事务
        Db::startTrans();
        try{
            $plan_integration_id = Db::name('sn_control_plan_integration')->insertGetId($addAr);
            if(!$plan_integration_id){$this->error('服务器错误，请重试~');}
            $plan_merge = Db::name('sn_control_plan_merge')->whereIn('id',$idArr)->update(['integration_id'=>$plan_integration_id]);
            if(!$plan_merge){$this->error('服务器错误，请重试~');}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('数据整合成功','',200);
    }
    
    
    
    
    //获取计划整合列表
    public function getIntegrationList(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if($data['authorize'] == 4){
            $where[] = ['m.admin_id','=',$data['admin_id']];
            $IntegrationList = Db::name('sn_control_plan_integration')->alias('m')->where($where)->limit(($data['page']-1)*$data['size'], $data['size'])->order('m.id desc')->select()->toArray();
        }elseif($data['authorize'] == 5){
            $where[] = ['m.examine_admin_id','=',$data['admin_id']];
            $IntegrationList = Db::name('sn_control_plan_integration')->alias('m')->where($where)->join('system_user u','m.examine_admin_id = u.id')->limit(($data['page']-1)*$data['size'], $data['size'])->order('m.id desc')->field('m.*,u.nickname,u.username')->select()->toArray();
        }else{
            $where[] = ['m.below_admin_id','=',$data['admin_id']];
            $IntegrationList = Db::name('sn_control_plan_integration')->alias('m')->where($where)->join('system_user u','m.below_admin_id = u.id')->limit(($data['page']-1)*$data['size'], $data['size'])->order('m.id desc')->field('m.*,u.nickname,u.username')->select()->toArray();
        }
        $this->success('ok',$IntegrationList,200);
    }
    
    
    //获取计划整合详情
    public function getIntegrationInfo(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        $where = array( 'id'=>$data['id']);
        $info = Db::name('sn_control_plan_integration')->where($where)->find();
        $merge_ids = Db::name('sn_control_plan_merge')->whereIn('id',$info['merge_ids'])->column('id,plan_ids');
        $ids = '';
        foreach ($merge_ids as $k=>$v){
            $ids .= $v['plan_ids'].',';
        }
        $plan_ids = rtrim($ids,",");
        
        $userInfo =  Db::name('system_user')->where(['id'=>$info['below_admin_id']])->find();
        if($userInfo){
            $info['below_admin_name'] = $userInfo['username'];
            $info['below_admin_nickname'] = $userInfo['nickname'];
        }else{
            $info['below_admin_name'] = '';
            $info['below_admin_nickname'] = '';
        }
        $plan_list = ControlPlanListModel::whereIn('plan_id',$plan_ids)->group('material_code')->field('*,sum(material_num) as material_num')->order('material_code')->select()->toArray();
        $total = 0;
        foreach ($plan_list as $k=>$v){
            $plan_list[$k]['info'] = ControlPlanListModel::where(['material_code'=>$v['material_code']])->whereIn('plan_id',$plan_ids)->field('merge_id,material_code,admin_name,sum(material_num) as material_num')->order('material_code')->column('admin_name,material_num');
            $plan_list[$k]['material_xjprice'] = sprintf("%01.2f", $v['material_price'] * $v['material_num']);
            $total += sprintf("%01.2f", $v['material_price'] * $v['material_num']);
        }
        $json = ['info'=>$info,'list'=>$plan_list,'total'=>$total];
        $this->success('ok',$json,200);
    }
    
    //计划整合审批
    public function getIntegrationToExamine(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!$data['authorize']){$this->error('请先登陆');}
        if(!$data['plan_status']){$this->error('请先选择下级审批权限');}
        if(!$data['id']){$this->error('缺少重要参数');}
        if(!$data['below_admin_id']){$this->error('请先选择下级审批人');}
        if($data['authorize'] == 4){$data['examine_admin_id'] = $data['below_admin_id'];}
        //开启事务
        Db::startTrans();
        try{
            $merge_ids = Db::name('sn_control_plan_merge')->where('integration_id',$data['id'])->column('plan_ids');
            $ids = '';
            foreach ($merge_ids as $k=>$v){
                $ids .= $v.',';
            }
            $plan_ids = explode(',',rtrim($ids,","));
            foreach ($plan_ids as $k=>$v){
                $saveArr[$k]['status'] = 1;
                $saveArr[$k]['time'] = date('Y-m-d H:i:s');
                $saveArr[$k]['to_reason'] = $data['remarks'];
                $saveArr[$k]['collect_id'] = $v;
                $saveArr[$k]['admin_id'] = $data['admin_id'];
                $saveArr[$k]['admin_name'] = $data['username'];
                $saveArr[$k]['admin_authorize'] = $data['authorize'];
                $saveArr[$k]['admin_nickname'] = $data['nickname'];
            }
            $ControlPlanItemModel = new ControlPlanItemModel();
            $plan_item = $ControlPlanItemModel->saveAll($saveArr);
            if(!$plan_item){$this->error('服务器错误');}
            unset($data['authorize']);
            unset($data['username']);
            unset($data['nickname']);
            $mer_id = Db::name('sn_control_plan_integration')->where('id',$data['id'])->update($data);
            if(!$mer_id){$this->error('服务器错误');}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('ok','',200);
    }
    
    
    //计划整合拒绝
    public function integrationRefusal(){
        $adminUser = input('post.');
        $integration_id = $adminUser['integration_id'];
        $refusal_cause = input('refusal_cause');
        $dateTime = date('Y-m-d H:i:s',time());
        $merge_ids = Db::name('sn_control_plan_merge')->where('integration_id',$integration_id)->column('plan_ids');
        $ids = '';
        foreach ($merge_ids as $k=>$v){
            $ids .= $v.',';
        }
        $plan_ids = explode(',',rtrim($ids,","));
        foreach ($plan_ids as $k=>$v){
            $saveArr[$k]['status'] = -1;
            $saveArr[$k]['time'] = $dateTime;
            $saveArr[$k]['to_reason'] = $refusal_cause;
            $saveArr[$k]['collect_id'] = $v;
            $saveArr[$k]['admin_id'] = $adminUser['admin_id'];
            $saveArr[$k]['admin_name'] = $adminUser['username'];
            $saveArr[$k]['admin_authorize'] = $adminUser['authorize'];
            $saveArr[$k]['admin_nickname'] = $adminUser['nickname'];
        }
        //开启事务
        Db::startTrans();
        try{
            //批量修改合并表计划
            $save_data = ['status' => '-1','reason_name'=>$adminUser['username'],'reason_id'=>$adminUser['admin_id'],'to_reason'=>$refusal_cause,'reason_time'=>$dateTime];
            $plan_zi_save = Db::name('sn_control_plan_merge')->where('integration_id',$integration_id)->update($save_data);
            if (!is_int($plan_zi_save)) {$this->error('服务器错误');}
            $ControlPlanItemModel = new ControlPlanItemModel();
            $plan_item = $ControlPlanItemModel->saveAll($saveArr);
            if (!$plan_item) {$this->error('服务器错误');}
            //批量修改主表计划
            $plan_list = ['status' => '-1','reason_name'=>$adminUser['username'],'reason_id'=>$adminUser['admin_id'],'to_reason'=>$refusal_cause,'reason_time'=>$dateTime,'merge_id'=>0];
            $plan_save = ControlPlanModel::whereIn('id',$plan_ids)->update($plan_list);
            if (!is_int($plan_save)) {$this->error('服务器错误');}
            //批量修改子表计划
            $plan_zi_save = ControlPlanListModel::whereIn('plan_id',$plan_ids)->update(['merge_id'=>0]);
            if (!is_int($plan_zi_save)) {$this->error('服务器错误');}
            $save_res = Db::name('sn_control_plan_integration')->where('id',$integration_id)->update($save_data);
            if (!is_int($save_res)) {$this->error('服务器错误');}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('ok','',200);
    }
    
    
    
     /**
     * 最终审核
     */
    public function setIntegrationresume()
    {
        $id = input('id');
        //获取合并计划ids
        $merge_ids = Db::name('sn_control_plan_integration')->where('id',$id)->value('merge_ids');
        //获取计划ids
        $plan_ids = Db::name('sn_control_plan_merge')->whereIn('id',$merge_ids)->column('plan_ids');
        $ids = '';
        foreach ($plan_ids as $k=>$v){
            $ids .= $v.',';
        }
        $plan_ids = explode(',',rtrim($ids,","));
        //$plan_lists = ControlPlanModel::whereIn('id',rtrim($ids,","))->column('id');
        $admin_user = input('post.');
        Db::startTrans();
        try{
            foreach ($plan_ids as $k=>$v){
    //            $res = $this->setEnterStorehouse($v);
                //获取计划所属人
                $admin_id = ControlPlanModel::where('id',$v)->value('admin_id');
                //创建库存表
                $sql = created_data('sn_enter_storehouse_'.$admin_id);
                Db::execute($sql);
                //获取计划子表数据
                $planList = ControlPlanListModel::where('plan_id',$v)->field('material_code,material_name,material_model,material_unit,material_price,material_num')->column('material_code,material_name,material_model,material_unit,material_price,material_num','material_code');
                //添加个人库存数据
                $adminStorehouse = Db::name('sn_enter_storehouse_'.$admin_id)->whereIn('material_code',array_column($planList,'material_code'))->column('*','material_code');
                if(count($planList) == count($adminStorehouse)){
                    foreach ($planList as $k1=>$v1){
                        $planList[$k1]['material_num'] = $v1['material_num'] + $adminStorehouse[$k1]['material_num'];
                    }
                    //先删除
                    $res = Db::name('sn_enter_storehouse_'.$admin_id)->whereIn('material_code',array_keys($planList))->delete();
                    if (!is_int($res)) {throw new \Exception("服务器错误");}
                    //新增数据
                    $res = Db::name('sn_enter_storehouse_'.$admin_id)->insertAll($planList);
                    if (!is_int($res)) {throw new \Exception("服务器错误");}
                }elseif (count($adminStorehouse) == 0){
                    //新增数据
                    $res = Db::name('sn_enter_storehouse_'.$admin_id)->insertAll($planList);
                    if (!is_int($res)) {throw new \Exception("服务器错误");}
                }else{
                    //比较两个数组的键名，并返回交集
                    $intersect_list = array_intersect_key($planList,$adminStorehouse);
                    foreach ($intersect_list as $ks=>$vs){
                        $intersect_list[$ks]['material_num'] = $vs['material_num'] + $adminStorehouse[$ks]['material_num'];
                    }
                    //先删除
                    $res = Db::name('sn_enter_storehouse_'.$admin_id)->whereIn('material_code',array_keys($intersect_list))->delete();
                    if (!is_int($res)) {throw new \Exception("服务器错误");}
                    //比较两个数组的键名，并返回差集
                    $diffList = array_diff_key($planList,$adminStorehouse);
                    //合并数据
                    $mergeList = array_merge($intersect_list,$diffList);
                    //新增数据
                    $res = Db::name('sn_enter_storehouse_'.$admin_id)->insertAll($mergeList);
                    if (!is_int($res)) {throw new \Exception("服务器错误");}
                }
                //主表数据修改
                $res_plan = ControlPlanModel::where('id',$v)->update(['status'=>1]);
                // 判断是否修改成功
                if (!is_int($res_plan)) {throw new \Exception("服务器错误");}
                // 流程数据添加
                $planTime = array('collect_id'=>$v,'status'=>1,'time'=>date('Y-m-d H:i:s',time()),'admin_name'=>$admin_user['username'],'admin_nickname'=>$admin_user['nickname'],'admin_authorize'=>$admin_user['authorize']);
    //            $where = ['collect_id'=>$plan_id,'admin_id'=>$admin_user['id']];
                $applyTime = Db::name('sn_control_plan_time')->insert($planTime);
                if (!$applyTime) {throw new \Exception("服务器错误");}
            }
            //更新合并表数据
            $merge_res = Db::name('sn_control_plan_merge')->whereIn('id',$merge_ids)->update(['status'=>1]);
            if (!is_int($merge_res)) {throw new \Exception("服务器错误");}
            //更新计划整合表数据
            $res_i = Db::name('sn_control_plan_integration')->whereIn('id',$id)->update(['status'=>1]);
            if (!is_int($res_i)) {throw new \Exception("服务器错误");}
            // 执行提交操作
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());
        }
        $this->success('数据更新成功');
    }
    
    


    /**
     * 确认入库
     */
    public function warehousing()
    {
        $data = input('post.');
        $plan_id = input('plan_id');
        if(!$data['admin_id']){$this->error('请先登陆');}
        $controlInfo = ControlPlanModel::where('id',$plan_id)->with('plan_list')->find()->toArray();
        $enter['title'] = $controlInfo['plan_title'];
        $enter['admin_id'] = $controlInfo['admin_id'];
        $enter['admin_name'] = $controlInfo['username'];
//        $enter['status'] = 1;
        $enter['storehouse_id'] = input('storehouse_id');
        $enter['plan_id'] = $plan_id;
        //开启事务
        Db::startTrans();
        try{
            $enter_id = EnterStorehouseModel::insertGetId($enter);
            if(!$enter_id) {throw new \Exception("服务器错误");}
            $cate_list = array();
            foreach ($controlInfo['plan_list'] as $k=>$v){
                $cate_list[] = array(
                    'material_code'=>$v['material_code'],
                    'material_name'=>$v['material_name'],
                    'material_model'=>$v['material_model'],
                    'material_unit'=>$v['material_unit'],
                    'material_price'=>$v['material_price'],
                    'material_num'=>$v['material_num'],
                    'material_xjprice'=>$v['material_xjprice'],
                    'enter_id'=>$enter_id,
                    'cate_id'=>$v['cate_id'],
                    'admin_id'=>$controlInfo['admin_id'],
                    'admin_name'=>$controlInfo['admin_name'],
                    'storehouse_id'=>input('storehouse_id'),
                    'create_at'=>date('Y-m-d H:i:s',time())
                );
            }
            //添加子表数据
            $res = EnterStorehouseItemModel::insertAll($cate_list);
            if(!$res) {throw new \Exception("服务器错误");}
            //修改计划状态
            $controRes = ControlPlanModel::where('id',$plan_id)->update(['enter_storehouse_status'=>1,'enter_storehouse_time'=>$cate_list['create_at']]);
            if(!$controRes) {throw new \Exception("服务器错误");}
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());die;
        }
        $this->success('入库成功！');
    }
    
    
    
     /**
     * 日志列表
     */
    public function planCollectLogList()
    {
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!$data['id']){$this->error('数据不存在');}
        $where = array('key'=>$data['id']);
        $info = Db::name('sn_control_plan_log')->where($where)->order('id desc')->select();
        $this->success("ok",$info,1);
    }


    /*
    * 数量/备注  日志添加
    */
    public function remarks(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        if(!$data['username']){$this->error('请先登陆');}
        if(!$data['index']){$this->error('数据不存在');}
        if(!$data['plan_id']){$this->error('计划不存在');}
        if(!$data['remarks']){$this->error("请填写备注");}
        if(!$data['numbers']){$this->error("请填写修改得数量");}
        $info = ControlPlanListModel::where('id',$data['index'])->find()->toArray();
        if($data['numbers']>=0 && $data['numbers'] != ''){
            if($info['material_num'] < $data['numbers']){
                $this->error('数量过大');
            }elseif($info['material_num'] == $data['numbers']){
                $this->error('无变化');
            }
            //开启事务
            Db::startTrans();
            try{
                $saveAll = array(
                    'material_num'=>$data['numbers'],
                    'material_xjprice'=>round($data['numbers'] * $info['material_price'],2),
                );
                $saveinfo = ControlPlanListModel::where('id',$data['index'])->update($saveAll);
                if($saveinfo === false){throw new \Exception("服务器错误");}
                //添加日志
                $insetAll = array(
                    'plan_id'=>$data['plan_id'],
                    'remarks'=>$data['remarks'],
                    'key'=>$data['index'],
                    'original_num'=>$info['material_num'],
                    'save_num'=>empty($data['numbers'])?$info['material_num']:$data['numbers'],
                    'admin_id'=>$data['admin_id'],
                    'admin_name'=>$data['username'],
                    'time'=>date('Y-m-d H:i:s',time())
                );
                $logId = Db::name('sn_control_plan_log')->insertGetId($insetAll);
                if(!$logId){throw new \Exception("服务器错误");}
                Db::commit();
            }catch(\Exception $e){
                // 回滚事务
                Db::rollback();
                // 获取提示信息
                $this->error($e->getMessage());die;
            }
            $this->success('数据更新成功');
        }
    }

    /**
     * 仓库列表
     */
    public function getWarehousingList(){
        $data = input('post.');
        if(!$data['admin_id']){$this->error('请先登陆');}
        $storehouse_list = StorehouseModel::where('deleted',0)->select()->toArray();
        $this->success('ok',$storehouse_list,1);
    }

    
    
    /**
     * 定时清理仓库数据（定时任务）
     */
    public function deleteCknum(){
        
        $data = Db::connect()->getTables();
        //开启事务
        Db::startTrans();
        try{
            foreach ($data as $k=>$v){
                $tabName = substr($v,-5);
                if(is_numeric($tabName)){
                    $res = Db::name('sn_enter_storehouse_'.$tabName)->delete(true);
                    if($res === false){throw new \Exception("服务器错误");}
                }
            }
            Db::commit();
        }catch(\Exception $e){
            // 回滚事务
            Db::rollback();
            // 获取提示信息
            $this->error($e->getMessage());die;
        }
    }
    





}
